import React from 'react';
import { SearchBar } from 'antd-mobile';
import Api from 'Utils/api';
import dialog from 'Utils/dialog';
import { connect } from 'react-redux';
import * as routerActions from 'react-router-redux';
import './../ShiAnMap/index.scss';
import './index.scss';

class NavigationSearch extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      organise: [],
      allOrganise: []
    }
  }
  componentWillMount() {
    this.initOrganise();
  }
  initOrganise() {
    const api = new Api({
      method: 'GET',
      path: '/depts/level',
      success: (res) => {
        this.setState({
          organise: res,
          allOrganise: res
        });
      },
      error: (msg) => {
        const buttons = [
          {
            label: '知道了',
            onClick: () => {},
          },
        ];
        dialog.open('提示', msg, buttons, 'center');
      }
    });
    api.run();
  }
  handleSearchOk(value) {
    const { allOrganise } = this.state;
    if (!value) {
      this.setState(preState => ({
        organise: preState.allOrganise
      }));
      return;
    }
    const searchOrganise = allOrganise.filter(org => org.name.indexOf(value.replace(/\s/g, '')) > -1);
    this.setState({
      organise: searchOrganise
    });
  }
  handleSelect(id) {
    sessionStorage.setItem('organiseId', id);
    this.props.dispatch(routerActions.goBack());
  }
  render() {
    const { organise } = this.state;
    return (
      <div className="navication-search-page">
        <div className="search-wrap">
          <SearchBar
            placeholder="请输入"
            onSubmit={this.handleSearchOk.bind(this)}
            focused
          />
        </div>
        <div className="search-content">
          {
            organise.length > 0 ?
              organise.map(item => (
                <div className="search-row" key={item.id} onClick={this.handleSelect.bind(this, item.id)}>{item.name}</div>
              )) : ''
          }
        </div>
      </div>
    )
  }
}

function mapStateToProps(state) {
  return {
    ...state.routing,
  };
}
export default connect(mapStateToProps)(NavigationSearch);
